package com.maple.utils.network.error

import android.net.ParseException
import android.text.TextUtils
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import com.maple.model.error.ERROR
import com.maple.utils.util.LogUtils
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException


object ExceptionHandle {

    fun handleException(e: Throwable,fail: ResponseThrowable?): ResponseThrowable {
        var ex = ResponseThrowable(ERROR.UNKNOWN)
        if (e is ResponseThrowable) {
            ex = e
        } else if (e is HttpException) {
            ex = ResponseThrowable(ERROR.HTTP_ERROR, e)
        } else if (e is JsonParseException
            || e is JSONException
            || e is ParseException || e is MalformedJsonException
        ) {
            ex = ResponseThrowable(ERROR.PARSE_ERROR, e)
        } else if (e is ConnectException) {
            ex = ResponseThrowable(ERROR.NETWORD_ERROR, e)
        } else if (e is javax.net.ssl.SSLException) {
            ex = ResponseThrowable(ERROR.SSL_ERROR, e)
        } else if (e is java.net.SocketTimeoutException) {
            ex = ResponseThrowable(ERROR.TIMEOUT_ERROR, e)
        } else if (e is java.net.UnknownHostException) {
            ex = ResponseThrowable(ERROR.TIMEOUT_ERROR, e)
        } else {
            if(fail != null){
                ex = ResponseThrowable(fail.code,fail.errMsg)
            }
        }
        return ex
    }

    fun handleException(e: String?): ResponseThrowable {
        LogUtils.logGGQ("======handleException=====>>${e}")
        var ex = ResponseThrowable(ERROR.SERVER_ERROR)
        if(!TextUtils.isEmpty(e) && e!!.contains("timeout")) {
            ex = ResponseThrowable(ERROR.TIMEOUT_ERROR)
        }
        return ex
    }
}